﻿using System;
using System.IO;
using System.Net;

namespace MalRec.Base.DataObject
{
    public class FileCache
    {
        public static string AppCacheDirectory { get; set; }

        static FileCache()
        {
            AppCacheDirectory = string.Format("{0}\\MyAnimelistRecommender\\Cache\\", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
        }

        public static string FromUrl(string url)
        {
            if (!Directory.Exists(AppCacheDirectory))
            {
                Directory.CreateDirectory(AppCacheDirectory);
            }

            var uri = new Uri(url);
            var localFile = string.Format("{0}{1}{2}", AppCacheDirectory, uri.Host, string.Join("\\", uri.Segments).Replace("/", ""));

            FileInfo fi = new FileInfo(localFile);
            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }

            if (!fi.Exists || fi.Length == 0)
            {
                try
                {
                    new WebClient().DownloadFile(url, localFile);
                }
                catch
                {
                }
            }

            return localFile;
        }
    }
}